package com.cems.controller.Entrust;

import com.cems.mapper.EntrustMapper;
import com.cems.mapper.MessageMapper;
import com.cems.pojo.ComUser;
import com.cems.pojo.SysEntrust;
import com.cems.pojo.SysUser;
import com.cems.service.EntrustService;
import com.cems.util.DateUtil;
import com.cems.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName EntrustController
 * @Author 陈新予(blank)
 * @Date 2021/5/20
 * @Version 1.0
 */
@Controller
public class EntrustController {
    @Autowired
    EntrustService entrustService;
    @Autowired
    EntrustMapper entrustMapper;
    @Autowired
    UserService userService;
    @Autowired
    MessageMapper messageMapper;



    @GetMapping("toOrderReceiving")
    public String OrderReceiving(HttpSession session) {
        List<SysEntrust> entrusts = entrustService.getLeisureEntrusts();
        if (entrusts.size() == 0) {
            return "User/zhanshimeiy2";
        }
        int pages;
        if (entrusts.size() % 5 == 0) {
            pages = entrusts.size() / 5;
        } else {
            pages = entrusts.size() / 5 + 1;
        }
        System.out.println(entrusts.size());
        System.out.println(pages);
        ArrayList<String> entrustTypeList = new ArrayList<>();
        ArrayList<String> entrustDataList = new ArrayList<>();
        ArrayList<String> entrustUserList = new ArrayList<>();
        ArrayList<String> entrustIdList = new ArrayList<>();
        ArrayList<String> entrustStartTime = new ArrayList<>();
        ArrayList<String> entrustEndTime = new ArrayList<>();
        ArrayList<String> entrustMoney = new ArrayList<>();
        for (SysEntrust entrust : entrusts) {
            if (entrust.getGmtEnd().after(new Date())) {
                entrustIdList.add(String.valueOf(entrust.getEntrustId()));
                entrustTypeList.add(entrustMapper.getEntrustTypeById(Integer.parseInt(entrust.getEntType())));
                entrustDataList.add(entrust.getEntData());
                entrustUserList.add(entrustMapper.getEntrustUserById(entrust.getEntConsignor()));
                entrustStartTime.add(new DateUtil().dateToString(entrust.getGmtCreate()));
                entrustEndTime.add(new DateUtil().dateToString(entrust.getGmtEnd()));
                entrustMoney.add(String.valueOf(entrust.getEntMoney()));
            }
        }
        session.setAttribute("entrustIdList", entrustIdList);
        session.setAttribute("entrustMoney", entrustMoney);
        session.setAttribute("entrustTypeList", entrustTypeList);
        session.setAttribute("entrustDataList", entrustDataList);
        session.setAttribute("entrustUserList", entrustUserList);
        session.setAttribute("entrustStartTime", entrustStartTime);
        session.setAttribute("entrustEndTime", entrustEndTime);
        session.setAttribute("LeisureEntrustspages", pages);
        return "font/jiedan/orderReceiving";
    }

    @GetMapping("toOrderInfo")
    public String toOrderInfo(String id, Model model) {
        SysEntrust ent = entrustMapper.getEntByID(Integer.parseInt(id));
        model.addAttribute("userPname", entrustMapper.getEntrustUserById(ent.getEntConsignor()));
        model.addAttribute("userData", ent.getEntData());
        model.addAttribute("userCTime", new DateUtil().dateToString(ent.getGmtCreate()));
        model.addAttribute("userEtime", new DateUtil().dateToString(ent.getGmtCreate()));
        model.addAttribute("EntId", id);
        model.addAttribute("EntType", entrustMapper.getEntrustTypeById(Integer.parseInt(id)));
        model.addAttribute("userMoney", ent.getEntMoney());
        return "font/jiedan/orderInfo";
    }

    @GetMapping("getOrder")
    @ResponseBody
    public int getOrderById(int id, HttpSession session) {
        try {
            SysUser user = (SysUser) session.getAttribute("user");
            int userId = user.getId();
            entrustService.GetEntrust(id, userId);
            entrustService.userRevEntrustStatus(id, "已被接");
            SysEntrust leisureEntrustsByEntId = entrustService.getLeisureEntrustsByEntId(id);
            Map<String,Object> map = new HashMap<>();
            map.put("userId",leisureEntrustsByEntId.getEntConsignor());
            map.put("userMessage","您的委托已经被接");
            messageMapper.addMessage(map);
            return 1;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    @GetMapping("myentIngOrder")
    public String MyEntIngOrder(Model model, HttpSession session, int id) {
        List<SysEntrust> entrusts = entrustService.getMyEntIng(id);
        if (entrusts.size() == 0) {
            return "User/zhanshimeiy";
        }
        int pages;
        if (entrusts.size() % 5 == 0) {
            pages = entrusts.size() / 5;
        } else {
            pages = entrusts.size() / 5 + 1;
        }
        ArrayList<String> entrustTypeList = new ArrayList<>();
        ArrayList<String> entrustDataList = new ArrayList<>();
        ArrayList<String> entrustUserList = new ArrayList<>();
        ArrayList<String> entrustIdList = new ArrayList<>();
        ArrayList<String> entrustStartTime = new ArrayList<>();
        ArrayList<String> entrustEndTime = new ArrayList<>();
        ArrayList<String> entrustMoney = new ArrayList<>();
        for (SysEntrust entrust : entrusts) {
            if (entrust.getGmtEnd().after(new Date())) {
                entrustIdList.add(String.valueOf(entrust.getEntrustId()));
                entrustTypeList.add(entrustMapper.getEntrustTypeById(Integer.parseInt(entrust.getEntType())));
                entrustDataList.add(entrust.getEntData());
                entrustUserList.add(entrustMapper.getEntrustUserById(entrust.getEntConsignor()));
                entrustStartTime.add(new DateUtil().dateToString(entrust.getGmtCreate()));
                entrustEndTime.add(new DateUtil().dateToString(entrust.getGmtEnd()));
                entrustMoney.add(String.valueOf(entrust.getEntMoney()));
            }
        }
        model.addAttribute("myentrustIdList", entrustIdList);
        model.addAttribute("myentrustMoney", entrustMoney);
        model.addAttribute("myentrustTypeList", entrustTypeList);
        model.addAttribute("myentrustDataList", entrustDataList);
        model.addAttribute("myentrustUserList", entrustUserList);
        model.addAttribute("myentrustStartTime", entrustStartTime);
        model.addAttribute("myentrustEndTime", entrustEndTime);
        model.addAttribute("myLeisureEntrustspages", pages);
        return "User/myOrdering";
    }

    @GetMapping("myentEndOrder")
    public String MyEntEndOrder(Model model, HttpSession session, int id) {
        List<SysEntrust> entrusts = entrustService.getMyEntEnd(id);
        if (entrusts.size() == 0) {
            return "User/zhanshimeiy";
        }
        int pages;
        if (entrusts.size() % 5 == 0) {
            pages = entrusts.size() / 5;
        } else {
            pages = entrusts.size() / 5 + 1;
        }
        ArrayList<String> entrustTypeList = new ArrayList<>();
        ArrayList<String> entrustDataList = new ArrayList<>();
        ArrayList<String> entrustUserList = new ArrayList<>();
        ArrayList<String> entrustIdList = new ArrayList<>();
        ArrayList<String> entrustStartTime = new ArrayList<>();
        ArrayList<String> entrustEndTime = new ArrayList<>();
        ArrayList<String> entrustMoney = new ArrayList<>();
        for (SysEntrust entrust : entrusts) {
            if (entrust.getGmtEnd().after(new Date())) {
                entrustIdList.add(String.valueOf(entrust.getEntrustId()));
                entrustTypeList.add(entrustMapper.getEntrustTypeById(Integer.parseInt(entrust.getEntType())));
                entrustDataList.add(entrust.getEntData());
                entrustUserList.add(entrustMapper.getEntrustUserById(entrust.getEntConsignor()));
                entrustStartTime.add(new DateUtil().dateToString(entrust.getGmtCreate()));
                entrustEndTime.add(new DateUtil().dateToString(entrust.getGmtEnd()));
                entrustMoney.add(String.valueOf(entrust.getEntMoney()));
            }
        }
        model.addAttribute("myentrustIdList", entrustIdList);
        model.addAttribute("myentrustMoney", entrustMoney);
        model.addAttribute("myentrustTypeList", entrustTypeList);
        model.addAttribute("myentrustDataList", entrustDataList);
        model.addAttribute("myentrustUserList", entrustUserList);
        model.addAttribute("myentrustStartTime", entrustStartTime);
        model.addAttribute("myentrustEndTime", entrustEndTime);
        model.addAttribute("myLeisureEntrustspages", pages);
        return "User/myOrderEd";
    }

    //进入发单页面
    @GetMapping("fadan/{id}")
    public String fadan(@PathVariable String id, Model model) {
        List<String> entrustTypes = entrustService.getEntrustTypes();
        model.addAttribute("Types", entrustTypes);
        model.addAttribute("userid", id);
        ComUser comUser = userService.selOneUser(Integer.valueOf(id));
        Integer userMoney = comUser.getUserMoney();
        model.addAttribute("money", userMoney);
        return "font/fadan/fadans";
    }

    //保存发单
    @GetMapping("preserve")
    @ResponseBody
    public String preserve(String hidden, String sele, String money, String time, String content) {
        System.out.println("hidden" + hidden);
        System.out.println("sele" + sele);
        System.out.println("money" + money);
        System.out.println("time" + time);
        int entrustTypeByType = entrustService.getEntrustTypeByType(sele);
        Map<String, Object> map = new HashMap<>();
        map.put("entConsignor", hidden);
        map.put("entTypeId", entrustTypeByType);
        map.put("entMoney", money);
        map.put("gmtEnd", time);
        map.put("entData", content);
        //保存
        entrustService.insertEntrust(map);
        ComUser comUser = userService.selOneUser(Integer.valueOf(hidden));
        map.put("userId", Integer.valueOf(hidden));
        map.put("userMoney", comUser.getUserMoney() - Integer.valueOf(money));
        userService.revOneUser(map);
        String s = String.valueOf(comUser.getUserMoney() - Integer.valueOf(money));
        return s;
    }

    //进入自己已发单页面
    @GetMapping("Issuedbill/{id}")
    public String Issuedbill(@PathVariable String id, Model model) {
        List<SysEntrust> leisureEntrustsById = entrustService.getLeisureEntrustsById(Integer.valueOf(id));
        leisureEntrustsById.forEach(System.out::println);
        model.addAttribute("EntrustsById", leisureEntrustsById);

        return "font/fadan/alreadyFaDan";
    }

    //删除自己的委托
    @GetMapping("del")
    @ResponseBody
    public String del(String id) { //委托id
        SysEntrust leisureEntrustsByEntId = entrustService.getLeisureEntrustsByEntId(Integer.valueOf(id));
        int i = entrustService.delLeisureEntrustById(Integer.valueOf(id));
        System.out.println("iiiiiiii的值是" + i);
        int d = -1;
        if (i != 0) {
            ComUser comUser = userService.selOneUser(leisureEntrustsByEntId.getEntConsignor());
            System.out.println("comUser::::" + comUser);
            Map<String, Object> map = new HashMap<>();
            map.put("userId", Integer.valueOf(comUser.getUserId()));
            map.put("userMoney", comUser.getUserMoney() + leisureEntrustsByEntId.getEntMoney());
            userService.revOneUser(map);
            map.put("userMessage","您的委托删除成功,退款将稍后到账");
            messageMapper.addMessage(map);
            d = comUser.getUserMoney() + leisureEntrustsByEntId.getEntMoney();
        }

        return String.valueOf(d);
    }

    //修改委托
    @GetMapping("revEn")
    @ResponseBody
    public String revEn(String id, Model model) {
        SysEntrust leisureEntrustsByEntId = entrustService.getLeisureEntrustsByEntId(Integer.valueOf(id));
        System.out.println("已被接".equals(leisureEntrustsByEntId.getEntPlan()));
        if ("已被接".equals(leisureEntrustsByEntId.getEntPlan())) {
            return "1";
        } else if ("已完成".equals(leisureEntrustsByEntId.getEntPlan())) {
            return "2";
        }
        else {
            return "ok";
        }
    }

    //去修改委托页面
    @GetMapping("toRevEn/{id}")
    public String toRevEn(@PathVariable String id,Model model){
        SysEntrust leisureEntrustsByEntId = entrustService.getLeisureEntrustsByEntId(Integer.valueOf(id));
        model.addAttribute("Entru", leisureEntrustsByEntId);
        ComUser comUser = userService.selOneUser(leisureEntrustsByEntId.getEntConsignor());
        model.addAttribute("Usermoney", comUser.getUserMoney());
        return "font/fadan/xgfadan";
    }

    //保存修改
    @GetMapping("preRevEn")
    @ResponseBody
    public String preRevEn(String hidden,String money,String time,String content,String money1){
        System.out.println("money的值是"+money);
        Map<String,Object> map = new HashMap<>();
        map.put("entData",content);
        map.put("entMoney",money1);
        map.put("gmtEnd",time);
        map.put("id",Integer.valueOf(hidden));
        SysEntrust leisureEntrustsByEntId = entrustService.getLeisureEntrustsByEntId(Integer.valueOf(hidden));
        map.put("userId", leisureEntrustsByEntId.getEntConsignor());
        map.put("userMoney", Integer.valueOf(money));
        userService.revOneUser(map);
        int i = entrustService.revLeisureEntrustById(map);

        return money;
    }

    //获得自己发布的所有单
    @GetMapping("getLeisureEntrustsById2")
    public String getLeisureEntrustsById2(String id, Model model) {
        List<SysEntrust> leisureEntrustsById2 = entrustService.getLeisureEntrustsById2(Integer.parseInt(id));
        model.addAttribute("EntrustsById2", leisureEntrustsById2);
        return "font/fadan/jiedan";
    }


    //管理员判断委托进度
    @GetMapping("upQuitEtrust")
    @ResponseBody
    ////委托id->entrustId    //委托状态  entPlan   //委托人的ID   entConsignor
    //代理人的id  entAgent      //酬劳报酬   entMoney
    public String upEtrustStatus(Integer entrustId,
                                 String entPlan,
                                 Integer entConsignor,
                                 Integer entAgent,
                                 Double entMoney) {
        Double money1 = null;
        Double money2 = null;
        System.err.println("entPlan___>>>>+" + entPlan);
        String msg = "";
        if (entPlan.equals("已完成")) {
            //订单已完成 不可推荐
            msg += "ok";
            System.err.println("msgmsgmsgmsg==??" + msg);
            return msg;
        } else {

            System.out.println("委托的价格是 entMoney" + entMoney);


            //给委托人反钱
            Map<String, Object> map = new HashMap<>();
            //查询委托人 当前的总余额
            ComUser comUser = userService.selOneUser(entConsignor);
            map.put("id", entConsignor);
            if (entAgent != -1) {
                money2 = entMoney * 0.9;
                map.put("userMoney", entMoney * 0.9 + comUser.getUserMoney());
            } else {
                money2 = entMoney;
                map.put("userMoney", entMoney + comUser.getUserMoney());
            }
            System.err.println(map);
            int count = entrustService.upQuitEtrustEntMoney(map);


            //给给代理人加钱一定的

            //查询委托人 当前的总余额
            ComUser comUser1 = userService.selOneUser(entAgent);
            map.put("id", entAgent);
            if (entAgent != -1) {

                money1 = entMoney * 0.1;

                map.put("userMoney", entMoney * 0.1 + comUser.getUserMoney());
            }
            int count1 = entrustService.upQuitEtrustEntMoney(map);


            if (entAgent != -1) {
                msg += "给委托人返回" + money2
                        + "给接单人返回+" + money1;
            } else {
                msg += "给委托人返回" + money2;
            }
            //删除委托信息
            SysEntrust leisureEntrustsByEntId = entrustService.getLeisureEntrustsByEntId(entrustId);
            map.put("userId",leisureEntrustsByEntId.getEntConsignor());
            map.put("userMessage","您的委托已被管理员删除,退款将稍后到账");
            messageMapper.addMessage(map);
            map.put("userId",leisureEntrustsByEntId.getEntAgent());
            messageMapper.addMessage(map);
            Integer id = entrustId;
            entrustService.delLeisureEntrustById2(id);

            return msg;
        }
    }

    //获得自己发布的并且被接了的单
    @GetMapping("toJieDan/{id}")
    public String tojiedan(@PathVariable String id,Model model){  //这个id是发单人id
        List<SysEntrust> sysEntrusts = entrustService.AlreadyLeisureEntrustsByEntId(Integer.valueOf(id));
        sysEntrusts.forEach(System.out::println);
        model.addAttribute("AlreadyLeisureEntrustsByEntId",sysEntrusts);
        return "font/fadan/jiedan";
    }


    //通过委托
    @GetMapping("tongguo")
    @ResponseBody
    public String tongguo(String id,String useId){ //传的是委托的id
        SysEntrust leisureEntrustsByEntId = entrustService.getLeisureEntrustsByEntId(Integer.valueOf(id));
        ComUser comUser = userService.selOneUser(leisureEntrustsByEntId.getEntAgent());
        int i = comUser.getUserMoney() + leisureEntrustsByEntId.getEntMoney();
        Map<String,Object> map = new HashMap<>();
        map.put("userId",comUser.getUserId());
        map.put("userMoney",i);
        userService.revOneUser(map);
        entrustService.OkrevEntrustState(Integer.valueOf(id));
        map.put("userId",leisureEntrustsByEntId.getEntAgent());
        map.put("userMessage","您的任务已经通过,酬金将稍后到账");
        messageMapper.addMessage(map);
        return "";
    }
    //不通过委托
    @GetMapping("weitongguo")
    @ResponseBody
    public String weitongguo(String id){
        entrustService.NorevEntrustState(Integer.valueOf(id));
        return "";
    }

}
